<template>
  <div class="app-container">
    <el-card>
      <!--      标题以及按钮-->
      <div slot="header" class="clearfix">
        <el-row
          justify="space-between"
          type="flex"
        >
          <el-col :span="8"><span style="font-size: 20px;">购物车</span></el-col>
        </el-row>
      </div>
      <!--      标题以及按钮-->
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        :border="false"
        element-loading-text="Loading"
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <!-- 多选列 -->
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column align="center" label="图片">
          <template slot-scope="scope">
            <img
              :src="scope.row.ProductImageURL"
              alt="Product Image"
              style="max-width: 100px; max-height: 100px;"
            >
          </template>
        </el-table-column>

        <el-table-column align="center" label="产品名">
          <template slot-scope="scope">
            {{ scope.row.ProductName }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="价格" width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.ProductPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="数量" width="190">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.TotalQuantity" size="mini" :min="1" :max="100" label="描述文字" @change="handleChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="小计" width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.TotalPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              v-show="!scope.row.isEdit"
              circle
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <div>
        <!-- 购物车下部分 -->
        <div class="cart-actions">
          <div class="info-section">
            <div class="info-row">
              <span>已选择 <span class="highlight">{{ selectedItemCount }}</span> 件商品</span>
            </div>
            <div class="info-row">
              <span style="font-size: small;color: #97a8be">共计 <span>{{ totalItemCount }}</span> 件商品</span>
            </div>
          </div>
          <!-- 分割线 -->
          <el-divider direction="vertical" class="custom-divider" />
          <div class="info-section">
            <div class="info-row">
              <span>应付金额：<span class="highlight">￥{{ totalAmount }}</span></span>
            </div>
            <div class="info-row">
              <span style="font-size: small;color: #97a8be">应付金额不含邮费</span>
            </div>
          </div>
          <div class="action-buttons">
            <router-link :to="'/mall/checkout?' + anyRows.map(row => 'id=' + row.ProductID).join('&')" class="card-link">
              <el-button type="primary">现在结算</el-button>
            </router-link>
          </div>
        </div>
      </div>
      <!--分页工具条-->
      <el-pagination
        :background="background"
        :current-page="currentPage"
        :page-size="10"
        :page-sizes="[5, 10, 15, 20]"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script>

import { formatDate } from 'element-ui'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      background: true,
      // 每页显示的条数
      pageSize: 10,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      list: null,
      listLoading: true,
      // siteList: [],
      dialogFormVisible: false,
      dialogAddFormVisible: false,
      isLoading: false,
      formLabelWidth: '120px',
      // 已选择商品数量
      selectedItemCount: 0,
      // 应付总额
      totalAmount: 0,
      // 商品总数
      totalItemCount: 0,
      // 选中了哪几列
      anyRows: [],
      form: {
        // 产品的form
        CartID: 0,
        ProductID: '',
        ProductImageURL: '',
        ProductPrice: '',
        ProductDescription: '',
        TotalPrice: new Date(),
        TotalQuantity: 0
      }
    }
  },
  created() {
    this.getCart()
  },
  methods: {
    formatDate() {
      return formatDate
    },
    // 查询分页数据
    getCart() {
      this.$store.dispatch('cart/getCart', {
        Page: this.currentPage,
        ageSize: this.pageSize
      })
        .then((res) => {
          if (res.code === 0) {
            const { data } = res
            // 更新购物车列表
            this.list = data.rows
            this.listLoading = false
            this.totalCount = data.total
            // 计算总数、总金额等信息
            let totalItemCount = 0
            for (const item of this.list) {
              totalItemCount += item.TotalQuantity
            }
            // 更新本地状态
            this.totalItemCount = totalItemCount
          } else {
            this.$message.error(res.msg)
          }
        })
    },
    // 选中的商品的数值，如选中总额，选中总数
    handleSelectionChange(selection) {
      let selectedTotalItemCount = 0
      let selectedTotalAmount = 0
      this.anyRows = selection
      for (const item of selection) {
        selectedTotalItemCount += item.TotalQuantity
        selectedTotalAmount += item.TotalPrice
      }
      // 更新本地状态
      this.selectedItemCount = selectedTotalItemCount
      this.totalAmount = selectedTotalAmount
    },
    // 分页控件函数--start
    handleSizeChange(val) {
      this.pageSize = val
      this.getCart()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getCart()
    },
    // 分页控件函数--end
    // 计数器
    handleChange(row) {
      this.$store.dispatch('cart/updateCart', {
        productId: row.ProductID,
        quantity: row.TotalQuantity }
      ).then((res) => {
        if (res.code === 0) {
          this.dialogFormVisible = false
          this.getCart()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handleDelete(index, row) {
      this.$confirm(
        '此操作将删除商品：' +
        row.ProductName +
        ' 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$store.dispatch('cart/DeleteList', row).then((res) => {
            if (res.code === 0) {
              this.$message.success(res.msg)
              this.dialogFormVisible = false
              this.getCart()// Updated to use getCart instead of getProduct
            } else {
              this.$message.error(res.msg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }

  }
}

function time(time = +new Date()) {
  const date = new Date(time + 8 * 3600 * 1000)
  return date.toJSON().substr(0, 19).replace('T', ' ').replace(/-/g, '.')
}

time() // "2018.08.09 18:25:54"
</script>

<style scoped>
.cart-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.info-section {
  text-align: right;
  margin-right: 20px;
}

.action-buttons {
  margin-right: 20px;
}
.custom-divider {
  height: 50px; /* 设置分割线的高度为容器的高度 */
}
.highlight {
  color: red; /* 设置文字颜色为红色 */
  font-size: 1.2em; /* 设置字体大小为1.2倍（可以根据需要调整） */
}
</style>
